//
//  ViewController.m
//  03-24-net
//
//  Created by student on 16/3/24.
//  Copyright © 2016年 niit. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()<NSURLConnectionDataDelegate>
{
    NSMutableData *mData;
    int dataLength;
}
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    
    
    
    
    // 本机地址:
    // localhost
    // 127.0.0.1
    
    // 局域网地址
    // 192.168.13.2
    
    // 互联网上的
    //http://120.25.226.186:32812/

    
    
    
    NSURL *url=[NSURL URLWithString:@"http://192.168.13.31:8080/MJServer/login?username=123&pwd=123&method=get&type=JSON"];
    NSLog(@"协议:%@",url.scheme);
    NSLog(@"主机:%@",url.host);
     NSLog(@"路径:%@",url.relativePath);
     NSLog(@"路径:%@",url.path);
     NSLog(@"端口:%@",url.port);
     NSLog(@"请求:%@",url.query);
 
    
}
- (IBAction)btn:(id)sender {
    
    //1.网址
    
    NSURL *url =[NSURL URLWithString:@"http://localhost:8080/MJServer/login?username=123&pwd=123&method=get&type=JSON"];
    // 2. 请求对象
    NSURLRequest *request=[NSURLRequest requestWithURL:url];
    // 3. 发请求 (同步请求,等待服务器返回数据回来后继续向下运行)
//    NSData *data =[NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
//    
//    NSString *str=[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
//    NSLog(@"%@",str);
    
    NSURLResponse *response;
    NSError *error;
    
    NSDate *d1=[NSDate date];
    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
    NSDate *d2 =[NSDate date];
    NSTimeInterval t=[d2 timeIntervalSinceDate:d1];
    NSLog(@"花费了%0.3f秒",t);
    
    
    NSHTTPURLResponse *httpResponse = response;
    NSLog(@"状态码 %lu",httpResponse.statusCode);
    NSLog(@"响应头 %@",httpResponse.allHeaderFields);
    
    //数据->文字
    NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    // 显示结果
    NSLog(@"%@",str);
    
    
}
- (IBAction)btn2:(id)sender {
    //异步队列block方式
    
    //1.网址
    NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812//MJServer/login?username=123&pwd=123&method=get&type=JSON"];
    //2.请求对象
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
    //3. 发请求(异步请求,不会卡住线程，在后台请求数据,数据回来后，执行block里的处理方法)
    NSDate *d1 = [NSDate date];
    
    [NSURLConnection sendAsynchronousRequest: request queue: [NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        // 数据 -> 文字
        NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        // 显示结果
        NSLog(@"%@",str);
    }];
    NSDate *d2 = [NSDate date];
    NSTimeInterval t = [d2 timeIntervalSinceDate:d1];
    NSLog(@"花费了%.3f秒",t);
}
- (IBAction)btn3:(id)sender {
    //异步 代理方式
    // 1. 网址
    NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/resources/images/minion_02.png"];
    
    // 2. 请求对象
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    //3.发请求(异步请求,不会卡住主线程，在后台请求数据，数据回来后，执行block里的处理方法)
    NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
    
    //发出请求 (不会卡主页面)
    mData = [NSMutableData data];
    
    [connection start];

    
}
#pragma mark - NSURLConnectionData Delegate Method
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    NSHTTPURLResponse *h =response;
    NSLog(@"1.接收到服务器响应 %lu %@",h.statusCode,h.allHeaderFields);
    NSLog(@"数据总共大小是:%@",h.allHeaderFields[@"Content-Length"]);
    dataLength = [h.allHeaderFields[@"Content-Length"] intValue];
    
}
// 注意这个方法会多次运行，因为数据会被拆分成块发送，块的大小不是固定的
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
//    NSLog(@"接收到服务器返回的数据%lu",data.length);
    [mData appendData:data];
    NSLog(@"2.接收到服务器的数据%lu (进度:%i %%)",data.length,(int)(mData.length*100.0/dataLength));
}


- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSLog(@"3.接受完成,显示到界面");
    UIImage *image =[ UIImage imageWithData:mData];
    UIImageView *imageView = [[UIImageView alloc]initWithImage:image];
    [self.view addSubview:imageView];
    imageView.frame = CGRectMake(100, 100, image.size.width, image.size.height);
}
- (IBAction)btn4:(id)sender {
    //异步队列block方式
    //1. 网址 POST
    NSURL *url=[NSURL URLWithString:@"http://127.0.0.1:8080/MJServer/login"];
    //?username=123&pwd=123&method=get&type=JSON
    
    //2.请求对象
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = @"POST";//默认GET请求,指定为POST
    
    //字符串转换成数据放在请求体中
    NSData *postData=[@"username=123&pwd=123&method=get&type=JSON" dataUsingEncoding:NSUTF8StringEncoding];//NSString->NSData
    request.HTTPBody = postData;
    
    //3.发送请求(异步请求,不会卡住线程,在后台请求数据,数据回来后,执行block里的处理方法)
    
    NSDate *d1 = [NSDate date];
    
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        //数据->文字
        NSString *str= [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
        //显示结果
        NSLog(@"%@",str);
    }];
    NSDate *d2 = [NSDate date];
    NSTimeInterval t = [d2 timeIntervalSinceDate:d1];
    NSLog(@"花费了%.3f秒",t);

}


@end
